// access token 相关
import jwtDecode from "jwt-decode";

class Token {
  constructor() {
    this.type = "jwt"; // flask-jwt or oauth2
    this.access_token = null;
    this.acquire_timestamp = Math.round(new Date().getTime()) / 1000;
    this.expire_timestamp = Math.round(new Date().getTime()) / 1000;
  }

  static decodeExpStampFromJwtToken(access_token) {
    const decoded_jwt = jwtDecode(access_token);
    return decoded_jwt.exp;
  }

  checkExpire() {
    // 检查token是否过期
    if (!this.access_token) return false;
    const cur_timestamp = Math.round(new Date().getTime()) / 1000; // js的getTime返回的是millisecond精度的epoch
    if (cur_timestamp >= this.expire_timestamp) {
      return false;
    } else {
      return true;
    }
  }

  checkValid() {
    // 检查是否是有效的token
    return (
      this.checkExpire() && this.access_token && this.access_token.length > 0
    );
  }
}

export default Token;
export { Token };
